package com.zx.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.base.shiro.MyShiroRealm;
import com.zx.pojo.Role;
import com.zx.pojo.User;
import com.zx.service.RoleService;
import com.zx.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserController
 *
 * @author
 * @since 2022-12-03
 */
@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @RequestMapping("/list")
    public String list(Model model, String usrName, @RequestParam(required = false, defaultValue = "0") Long roleId, @RequestParam(defaultValue = "1") Long pageIndex) {
        List<Role> roles = roleService.list();

        Page page = new Page();
        page.setCurrent(pageIndex);
        User user = new User();
        user.setUsrName(usrName);
        user.setUsrRoleId(roleId);

//        IPage userPage = userService.getPage(page, user);
        IPage<User> userPage = userService.findUsers(usrName, roleId, page);

        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);
        model.addAttribute("roles", roles);
        model.addAttribute("userPager", userPage);

        return "user/list";
    }


    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    public String toAdd(Model model) {
        // 根据页面需要，查询所有角色信息并设置到作用域
        List<Role> roles = roleService.getAllRole();
        model.addAttribute("roles", roles);
        return "user/add";
    }

    /**
     * 跳转到修改页面
     */
    @GetMapping("/edit")
    @RequiresPermissions(value = "L060104")
    public String toEdit(Long usrId, Model model) {
        // 根据用户ID查询用户并设置到作用域
        User user = userService.getUserById(usrId);
        model.addAttribute("user", user);

        // 根据页面需要，查询所有角色信息并设置到作用域
        List<Role> roles = roleService.getAllRole();
        model.addAttribute("roles", roles);
        return "user/edit";
    }

    /**
     * 执行添加或修改保存
     */
    @PostMapping("/save")
    public String save(User user) {
        User newUser = userService.saveUser(user);
        log.info("/save --> {} : {}", newUser!=null, user.toString());

        // 清空权限缓存
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        realm.clearAllCachedAuthorizationInfo();
        return "redirect:/user/list";
    }

    /**
     * 执行删除
     */
    @ResponseBody // 直接将方法返回的对象转换为JSON数据格式响应前端，通常用于Ajax
    @GetMapping("/del/{usrId}")
    public Object del(@PathVariable("usrId") Long usrId) {
        Map<String, String> result = new HashMap<>(); // 返回结果
        boolean flag = userService.deleteUser(usrId);
        result.put("result", String.valueOf(flag));
        log.info("/del --> {} : {}", flag, usrId);

        // 清空权限缓存
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        realm.clearAllCachedAuthorizationInfo();
        return result; // data = {"delResult" : "true"}
    }
}
